using FairyGUI;
using GameFramework.Event;
using UnityEngine;
using UnityGameFramework.Runtime;

namespace StarForce
{
    public class MainPage : FGuiForm
    {
        private ProcedureMain m_ProcedureMain;
        
        private GTextField m_Grade;

        private GButton m_LeftBtn;

        private GButton m_RightBtn;
        
        private int m_Score;

        private bool m_IsTouch;

        protected override void OnInit(object userData)
        {
            base.OnInit(userData);
            m_Grade = UI.GetChild("n1").asTextField;
            m_LeftBtn = UI.GetChild("n5").asButton;
            m_RightBtn = UI.GetChild("n6").asButton;
        }

        protected override void OnOpen(object userData)
        {
            base.OnOpen(userData);
            m_ProcedureMain = (ProcedureMain) userData;
            if (m_ProcedureMain == null)
            {
                Log.Error("UserData is valid");
                return;
            }
            InitGameData();
            GameEntry.Event.Subscribe(UpScoreEventArgs.EventId,OnUpScore);
            GameEntry.Event.Subscribe(RestartGameEventGame.EventId,OnReStart);

            m_IsTouch = false;
            m_LeftBtn.onTouchBegin.Add(LeftBtnBegin);
            m_LeftBtn.onTouchEnd.Add(LeftBtnBeginEnd);
            m_RightBtn.onTouchBegin.Add(RightBtnBegin);
            m_RightBtn.onTouchEnd.Add(RightBtnBeginEnd);
        }

        private void LeftBtnBegin()
        {
            if (m_IsTouch)
            {
                return;
            }

            m_IsTouch = true;
            GameEntry.InputModule.StartTouch(-0.8f);
        }

        private void LeftBtnBeginEnd()
        {
            m_IsTouch = false;
            GameEntry.InputModule.EndTouch();
        }
        
        private void RightBtnBegin()
        {
            if (m_IsTouch)
            {
                return;
            }
            m_IsTouch = true;
            GameEntry.InputModule.StartTouch(0.8f);
        }

        private void RightBtnBeginEnd()
        {
            m_IsTouch = false;
            GameEntry.InputModule.EndTouch();
        }
        
        /// <summary>
        /// 初始化数据
        /// </summary>
        private void InitGameData()
        {
            m_Score = 0;
            m_Grade.text =m_Score.ToString();
        }

        protected override void OnClose(bool isShutdown, object userData)
        {
            base.OnClose(isShutdown, userData);
            GameEntry.Event.Unsubscribe(UpScoreEventArgs.EventId,OnUpScore);
            GameEntry.Event.Unsubscribe(RestartGameEventGame.EventId,OnReStart);
        }

        private void OnReStart(object sender, GameEventArgs e)
        {
            InitGameData();
        }

        private void OnUpScore(object sender, GameEventArgs e)
        {
            UpScoreEventArgs result = (UpScoreEventArgs) e;
            m_Score += result.Score;
            m_Grade.text =m_Score.ToString();
        }
    }
}